package com.qu.ListControl.materialdesign;

import android.graphics.Rect;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qu.ListControl.R;
import com.qu.ListControl.materialdesign.fragment.Test1Fragment;
import com.qu.ListControl.materialdesign.fragment.Test2Fragment;
import com.qu.ListControl.materialdesign.fragment.Test3Fragment;
import com.qu.ListControl.materialdesign.fragment.Test4Fragment;
import com.qu.ListControl.widget.SolarSystemView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 测试material design的新特性
 */
public class TestMaterialActivity extends AppCompatActivity implements View.OnClickListener{
     @BindView(R.id.mAppBarLayout)
     AppBarLayout mAppBarLayout;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_portrait)
    ImageView mPortrait;
    @BindView(R.id.view_solar_system)
    SolarSystemView mSolarSystem;
    @BindView(R.id.iv_picture)
    ImageView mLogoPortrait;
    @BindView(R.id.title)
    TextView mLogoNick;
    @BindView(R.id.view_divider)
    View mDivider;
    @BindView(R.id.layout_tab)
    TabLayout mTabLayout;
    @BindView(R.id.mViewPager)
    ViewPager mViewPager;
    private TabLayoutOffsetChangeListener mOffsetChangerListener;
    private List<Pair<String,Fragment>> fragments;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_material);
        ButterKnife.bind(this);
        initWidget();
    }

    private void initWidget() {
        mToolbar.setTitle("");
        mToolbar.setSubtitle("");
        mToolbar.setNavigationIcon(R.mipmap.btn_back_normal);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("TAG","到这里来了.......................");
                finish();
            }
        });
        mAppBarLayout.addOnOffsetChangedListener(mOffsetChangerListener = new TabLayoutOffsetChangeListener());
        //对太阳星系的转动
        mPortrait.post(new Runnable() {
            @Override
            public void run() {
                int mStatusBarHeight = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Rect rectangle = new Rect();
                    Window window = getWindow();
                    window.getDecorView().getWindowVisibleDisplayFrame(rectangle);
                    mStatusBarHeight = rectangle.top;
                }

                float x = mPortrait.getX();
                float y = mPortrait.getY();
                ViewGroup parent = (ViewGroup) mPortrait.getParent();
                float px = x + parent.getX() + mPortrait.getWidth() / 2;
                float py = y + parent.getY() + mPortrait.getHeight() / 2 + mStatusBarHeight;
                int mMaxRadius = (int) (mSolarSystem.getHeight() - py + 50);

                int r = mPortrait.getWidth() / 2;
                Random random = new Random(System.currentTimeMillis());
                for (int i = 60, radius = r + i; ; i = (int) (i * 1.4), radius += i) {
                    SolarSystemView.Planet planet = new SolarSystemView.Planet();
                    planet.setClockwise(random.nextInt(10) % 2 == 0);
                    planet.setAngleRate((random.nextInt(35) + 1) / 1000.f);
                    planet.setRadius(radius);
                    mSolarSystem.addPlanets(planet);
                    if (radius > mMaxRadius) break;
                }
                mSolarSystem.setPivotPoint(px, py);
                float ry = mSolarSystem.getHeight() - py;
                double rx = Math.pow(px * px + ry * ry, 1.f / 2.f);
                mSolarSystem.setRadialGradient(px, py, (float) rx, 0XFF24CF5F, 0XFF20B955);
            }
        });
        mOffsetChangerListener.resetRange();

        injectDataToViewPager();
    }

    /**
     * 绑定数据到ViewPager(自定义TabView)
     */
    private void injectDataToViewPager() {
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView("0", "测试1")));
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView("0", "测试2")));
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView("0", "测试3")));
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView("0", "测试4")));
        mTabLayout.setVisibility(View.VISIBLE);
        if (fragments == null) {
            fragments = new ArrayList<>();
            fragments.add(new Pair<>(
                    String.format("%s\n测试1", 0),
                    (Fragment) Test1Fragment.newInstance()));
            fragments.add(new Pair<>(
                    String.format("%s\n测试2", 0),
                    (Fragment) Test2Fragment.newInstance()));
            fragments.add(new Pair<>(
                    String.format("%s\n测试3", 0),
                    (Fragment) Test3Fragment.newInstance()));
            fragments.add(new Pair<>(
                    String.format("%s\n测试4", 0),
                    (Fragment) Test4Fragment.newInstance()));
            mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    return fragments.get(position).second;
                }

                @Override
                public int getCount() {
                    return fragments.size();
                }

                @Override
                public CharSequence getPageTitle(int position) {
                    return fragments.get(position).first;
                }
            });

            mTabLayout.setupWithViewPager(mViewPager);
            // TabLayout will remove up all tabs after setted up view pager
            // so we set it again
            mTabLayout.getTabAt(0).setCustomView(getTabView(formatNumeric(1000), "测试1"));
            mTabLayout.getTabAt(1).setCustomView(getTabView(formatNumeric(200), "测试2"));
            mTabLayout.getTabAt(2).setCustomView(getTabView(formatNumeric(300), "测试3"));
            mTabLayout.getTabAt(3).setCustomView(getTabView(formatNumeric(40000), "测试4"));
        } else { // when request user detail info successfully
            setupTabText(mTabLayout.getTabAt(0), 1000);
            setupTabText(mTabLayout.getTabAt(1), 200);
            setupTabText(mTabLayout.getTabAt(2), 300);
            setupTabText(mTabLayout.getTabAt(3), 40000);
        }
    }
    private View getTabView(String cs, String tag) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item_other_user, mTabLayout, false);
        TabViewHolder holder = new TabViewHolder(view);
        holder.mViewCount.setText(cs);
        holder.mViewTag.setText(tag);
        view.setTag(holder);
        return view;
    }

    private static class TabViewHolder {
        private TextView mViewCount;
        private TextView mViewTag;

        public TabViewHolder(View view) {
            mViewCount = (TextView) view.findViewById(R.id.tv_count);
            mViewTag = (TextView) view.findViewById(R.id.tv_tag);
        }
    }

    /**
     * 对数据进行格式化
     * @param count
     * @return
     */
    private String formatNumeric(int count) {
        if (count > 1000) {
            int a = count / 100;
            int b = a % 10;
            int c = a / 10;
            String str;
            if (c <= 9 && b != 0) str = c + "." + b;
            else str = String.valueOf(c);
            return str + "k";
        } else {
            return String.valueOf(count);
        }
    }

    /**
     * 设置TabLayout的数据
     * @param tab
     * @param count
     */
    private void setupTabText(TabLayout.Tab tab, int count) {
        View view = tab.getCustomView();
        if (view == null) return;
        TabViewHolder holder = (TabViewHolder) view.getTag();
        holder.mViewCount.setText(formatNumeric(count));
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.view_solar_system){
            Toast.makeText(TestMaterialActivity.this,"我被点击了1111222222222",Toast.LENGTH_SHORT);
        }
    }

    /**
     * AppBarLayout的滑动监听---根据滑动的位置最子视图执行对应的动作
     */
    private class TabLayoutOffsetChangeListener implements AppBarLayout.OnOffsetChangedListener {
        boolean isShow = false;
        int mScrollRange = -1;//子视图移动的位置

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (mScrollRange == -1) {
                mScrollRange = appBarLayout.getTotalScrollRange();
            }
            if (mScrollRange + verticalOffset == 0) { //收拢的条件
                mLogoNick.setVisibility(View.VISIBLE);
                mLogoPortrait.setVisibility(View.VISIBLE);
                mDivider.setVisibility(View.GONE);
                isShow = true;
            } else if (isShow) {  //展开的条件
                mLogoNick.setVisibility(View.GONE);
                mLogoPortrait.setVisibility(View.GONE);
                mDivider.setVisibility(View.VISIBLE);
                isShow = false;
            }
            mTabLayout.getBackground().setAlpha(Math.round(255 - Math.abs(verticalOffset) / (float) mScrollRange * 255));
        }
        public void resetRange() {
            mScrollRange = -1;
        }
    }
    //创建menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //加载菜单的布局
        getMenuInflater().inflate(R.menu.menu_other_user,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.iv_fans){ //私信
              //处理相对应的逻辑
              Toast.makeText(this,"我的私信千千万万",Toast.LENGTH_SHORT).show();
        }else if(item.getItemId() == R.id.iv_fallow){ //粉丝

            Toast.makeText(this,"我的粉丝千千万万",Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}
